using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Transactions;
using Hermes.Framework.FileSystem;

namespace Hermes.Framework.Implementation
{
    public abstract class TxOperationTemplate : ITransactableOperation
    {
        protected string srcFileName;

        protected string dstFileName;

        protected string shadowFileName;

        protected abstract void Operate();

        public abstract void Commit();

        public abstract void Rollback();
        
        protected INonTransactableFileSystem fileSystem = null;

        protected IResourceManager resourceManager = null;

        public INonTransactableFileSystem FileSystem
        {
            set
            {
                this.fileSystem = value;
            }
        }

        public IResourceManager ResourceManager
        {
            set
            {
                this.resourceManager = value;
            }
        }

        public TxOperationTemplate(string dstFileName)
        {
            this.srcFileName = dstFileName;
            this.dstFileName = dstFileName;
        }

        public TxOperationTemplate(string srcFileName, string dstFileName)
        {
            this.srcFileName = srcFileName;
            this.dstFileName = dstFileName;
        }

        public void Execute(string dstFileName)
        {
            this.Execute(dstFileName, dstFileName);
        }

        public void Execute(string srcFileName, string dstFileName)
        {
            // this.Enlist();
            this.resourceManager.Enlist();

            this.srcFileName = srcFileName;
            this.dstFileName = dstFileName;

            this.shadowFileName = dstFileName + ".shadow";

            this.resourceManager.WriteRedoLog(this);
            this.Operate();
            this.resourceManager.WriteUndoLog(this);
        }
    }
}
